//! Pipit 标准库函数注册表
//! 
//! 本文件定义了所有支持的标准库函数名称，供编译器和虚拟机共同使用。

use std::collections::{HashSet, HashMap};
use once_cell::sync::Lazy;

/// 标准库函数名称集合
pub struct StdlibRegistry {
    /// 所有标准库函数名称的集合
    pub functions: HashSet<String>,
    /// 按模块分类的标准库函数
    pub modules: HashMap<String, HashSet<String>>,
}

impl Default for StdlibRegistry {
    fn default() -> Self {
        let mut registry = StdlibRegistry {
            functions: HashSet::new(),
            modules: HashMap::new(),
        };
        
        // 初始化所有标准库函数
        registry.initialize();
        registry
    }
}

impl StdlibRegistry {
    /// 创建新的标准库注册表
    pub fn new() -> Self {
        Default::default()
    }
    
    /// 初始化所有标准库函数
    fn initialize(&mut self) {
        // IO 模块
        self.add_module_functions("io", &[
            "pipit_fopen", "pipit_fclose", "pipit_fread", "pipit_fwrite", 
            "pipit_feof", "pipit_file_size", "pipit_read_file", "pipit_write_file",
            "pipit_file_exists", "pipit_remove_file", "pipit_rename_file", "pipit_getcwd",
            "pipit_mkdir", "pipit_rmdir", "pipit_get_file_info", "pipit_read_buffer",
            "pipit_write_buffer", "pipit_line_reader_open", "pipit_line_reader_next",
            "pipit_line_reader_close"
        ]);
        
        // Math 模块
        self.add_module_functions("math", &[
            "pipit_add", "pipit_subtract", "pipit_multiply", "pipit_divide",
            "pipit_modulo", "pipit_power", "pipit_sqrt", "pipit_abs",
            "pipit_max", "pipit_min", "pipit_round", "pipit_floor",
            "pipit_ceil", "pipit_random", "pipit_srand", "pipit_random_range",
            "pipit_sin", "pipit_cos", "pipit_tan", "pipit_log",
            "pipit_log10", "pipit_exp", "pipit_random_float", "pipit_is_prime",
            "pipit_factorial", "pipit_gcd", "pipit_lcm", "pipit_degrees_to_radians",
            "pipit_radians_to_degrees"
        ]);
        
        // String 模块
        self.add_module_functions("string", &[
            "pipit_string_length", "pipit_string_concat", "pipit_string_to_upper", 
            "pipit_string_to_lower", "pipit_string_compare", "pipit_string_find",
            "pipit_string_split", "pipit_string_replace", "pipit_string_trim",
            "pipit_string_substring", "pipit_string_starts_with", "pipit_string_ends_with",
            "pipit_string_to_int", "pipit_string_to_double", "pipit_string_format",
            "pipit_string_split_free", "strdup"
        ]);
        
        // OS 模块
        self.add_module_functions("os", &[
            "pipit_os_system", "pipit_os_getcwd", "pipit_os_chdir", "pipit_os_mkdir",
            "pipit_os_remove", "pipit_os_stat", "pipit_os_filesize", "pipit_os_timestamp"
        ]);
        
        // Syscall 模块
        self.add_module_functions("syscall", &[
            "pipit_syscall_read_int", "pipit_syscall_read_float", "pipit_syscall_read_string",
            "pipit_syscall_read_line", "pipit_syscall_print_int", "pipit_syscall_print_float",
            "pipit_syscall_print_string", "pipit_syscall_print_line", "pipit_syscall_getenv",
            "pipit_syscall_system"
        ]);
        
        // Concurrent 模块
        self.add_module_functions("concurrent", &[
            "pipit_sleep", "pipit_thread_create", "pipit_thread_join", "pipit_thread_id",
            "pipit_mutex_create", "pipit_mutex_destroy", "pipit_mutex_lock", "pipit_mutex_unlock"
        ]);
        
        // JSON 模块
        self.add_module_functions("json", &[
            "json_create_null", "json_create_bool", "json_create_number", "json_create_string",
            "json_array_create", "json_array_append", "json_object_create", "json_object_set",
            "json_serialize_string"
        ]);
        
        // Collections 模块
        self.add_module_functions("collections", &[
            "pipit_vector_create", "pipit_vector_push_back", "pipit_vector_get",
            "pipit_vector_size", "pipit_vector_destroy", "pipit_hashmap_create",
            "pipit_hashmap_set", "pipit_hashmap_get", "pipit_list_create",
            "pipit_list_push_back", "pipit_list_get", "pipit_list_size",
            "pipit_stack_create", "pipit_stack_push", "pipit_stack_pop",
            "pipit_queue_create", "pipit_queue_enqueue", "pipit_queue_dequeue"
        ]);
        
        // Crypto 模块
        self.add_module_functions("crypto", &[
            "pipit_crypto_xor_encrypt", "pipit_crypto_caesar_encrypt", "pipit_crypto_checksum",
            "pipit_crypto_random_bytes", "pipit_crypto_base64_encode", "pipit_crypto_hmac",
            "pipit_crypto_password_strength"
        ]);
        
        // DateTime 模块
        self.add_module_functions("datetime", &[
            "pipit_datetime_now", "pipit_datetime_current", "pipit_datetime_create",
            "pipit_datetime_format", "pipit_datetime_parse", "pipit_datetime_diff",
            "pipit_datetime_add_delta", "pipit_datetime_weekday", "pipit_datetime_is_leap_year",
            "pipit_datetime_days_in_month", "pipit_datetime_to_timestamp", 
            "pipit_datetime_from_timestamp", "pipit_timer_create", "pipit_timer_start",
            "pipit_timer_stop", "pipit_timer_elapsed"
        ]);
        
        // 常用标准库函数（简短名称）
        self.add_functions(&[
            "read_int", "read_float", "get_time", "print", "println",
            "vsnprintf", "rmdir", "getcwd", "strdup"
        ]);
    }
    
    /// 添加一组模块函数
    fn add_module_functions(&mut self, module_name: &str, function_names: &[&str]) {
        let module_set = self.modules.entry(module_name.to_string()).or_insert_with(HashSet::new);
        
        for &func_name in function_names {
            self.functions.insert(func_name.to_string());
            module_set.insert(func_name.to_string());
        }
    }
    
    /// 添加一组函数（不属于特定模块）
    fn add_functions(&mut self, function_names: &[&str]) {
        for &func_name in function_names {
            self.functions.insert(func_name.to_string());
        }
    }
    
    /// 检查函数是否是标准库函数
    pub fn is_stdlib_function(&self, name: &str) -> bool {
        self.functions.contains(name)
    }
    
    /// 获取指定模块的所有函数
    pub fn get_module_functions(&self, module_name: &str) -> Option<&HashSet<String>> {
        self.modules.get(module_name)
    }
    
    /// 获取所有标准库函数的名称
    pub fn get_all_functions(&self) -> &HashSet<String> {
        &self.functions
    }
}

/// 全局标准库注册表实例
pub static GLOBAL_STDLIB_REGISTRY: Lazy<StdlibRegistry> = 
    Lazy::new(StdlibRegistry::new);

/// 检查函数是否是标准库函数的便捷方法
pub fn is_stdlib_function(name: &str) -> bool {
    GLOBAL_STDLIB_REGISTRY.is_stdlib_function(name)
}